package yl.hs.bmipfull.service.equipment.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import yl.hs.bmipfull.daos.equipment.IEquipmentDAO;
import yl.hs.bmipfull.pojo.equipment.EquipmentEntity;
import yl.hs.bmipfull.pojo.equipment.EquipmentLogEntity;
import yl.hs.bmipfull.service.equipment.IEquipmentService;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.MsgType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;
import yl.hs.bmipfull.viewmodels.SubmitModel;

import java.util.Date;
import java.util.List;
import java.util.Map;

/*
 * EquipmentServiceImpl
 * @category
 * @author 谢景广
 * @date 2022-11-14
 */
@Service
public class EquipmentServiceImpl extends EquipmentBaseService implements IEquipmentService {

    @Override
    public PageResult<EquipmentEntity> queryPage(PageQuery query, int rowNum, int page) {
        PageResult<EquipmentEntity> result = new PageResult(rowNum);
        var filters = SearchFilterEngine.generateQueryList(query.getFilters(),
                EquipmentEntity.class);
        result.setPage(page);
        query.getQuery().put("querySkip", (page - 1) * rowNum);
        query.getQuery().put("pageSize", rowNum);
        query.checkSortSides(EquipmentEntity.class);
        query.getQuery().put("sortSide", String.join(",",query.getSortSides()));
        result.setRecords(equipmentDAO.queryCountByCondition(query.getQuery(),filters));
        result.setData(equipmentDAO.queryListByCondition(query.getQuery(),filters));
        return result;
    }


    @Override
    public Integer saveEquipment(SubmitModel model) throws Exception {
        var result = 0;
        EquipmentEntity entity;
        if(Tl.isEmpty(model.getSn())){
            entity = new EquipmentEntity();
            Tl.getChangeLog(entity,model.getData());
            entity.setSn(queryNewSN(entity.getClass()));
            result = equipmentDAO.insertNew(entity);
            writeLog(ActionType.CREATE,entity.getSn(),"",null,entity.getClass());
        }
        else{
            entity = equipmentDAO.findBySN(model.getSn());
            var backJson = entity.toJson();
            var changeLog = Tl.getChangeLog(entity,model.getData());
            writeLog(ActionType.UPDATE,entity.getSn(),changeLog,backJson,entity.getClass());
            result = equipmentDAO.update(entity);
        }
        if(result>0){
            var user = HsApp.getCurrent();
            saveGS(
                    entity.getSn(),
                    entity.getName(),
                    String.join(",",
                            entity.getName(),
                            entity.getDeviceNum(),
                            entity.getModule(),
                            entity.getDeviceParameter(),
                            entity.getSupplier(),
                            entity.getSupplyLink(),
                            entity.getSupplyLinker(),
                            entity.getOwnerDepart(),
                            entity.getPrincipalName(),
                            entity.getRemark()
                    ),
                    entity,
                    HsApp.getCurrent() != null ? HsApp.getCurrent().getUserSN() : null,
                    user.getOrganizationCode()
            );
        }
        return result;
    }

    @Override
    public Integer delete(String[] snArray ){
       var result = equipmentDAO.changeState(snArray,-1);
       if(result> 0){
           for (var sn : snArray) {
               writeLog(ActionType.DELETE, sn,"","",EquipmentEntity.class);
           }
           deleteGs(snArray);
       }
       return  result;
    }

    @Override
    public List<EquipmentLogEntity> queryLogByDataSn(String sn, String typeCode) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.checkSortSides(EquipmentLogEntity.class);
        if (!Tl.isEmpty(typeCode)) {
            pageQuery.getQuery().put("typeCode", typeCode);
        }
        return logDao.queryListByCondition(pageQuery.getQuery(), sn);
    }

    @Override
    public List<Map<String,Object>> queryEquipmentMRRecord(String equipmentSN){
       return equipmentDAO.queryEquipmentMRRecord(equipmentSN);
    }


    @Override
    @Scheduled(cron = "5 5 8 * * ?")
    public void checkEquipment(){
        List<EquipmentEntity> dataList = equipmentDAO.queryAllEquipment();
        for (var device : dataList){
            try {
                Date startTime;
                if (device.getLastTime() != null) {
                    startTime = device.getLastTime();
                } else {
                    startTime = device.getBuyDate();
                }
                if (device.getTimeUnit() == 1) {

                    var days = ((new Date()).getTime() - startTime.getTime()) / (1000 * 60 * 60 * 24);
                    if (days == 7 || days == 3 || days == 1) {
                        sendMsg(MsgType.Instant, device.getPrincipalSN(), device.getName() + "【" + device.getDeviceNum() + "】的设备还有" + days + "天需要保养，请提前做好保养准备",
                                device.getName() + "【" + device.getDeviceNum() + "】的设备还有" + days + "天需要保养，请提前做好保养准备");

                    }
                }
            }
            catch (Exception ee){
                log.error("检测设备维护周期时发生错误",ee);
            }
        }
    }
    @Override
    public List<EquipmentEntity> queryByorderSn(String sn) {
        return equipmentDAO.queryByorderSn(sn);
    }

    private IEquipmentDAO equipmentDAO;

    @Autowired
    public void setEquipmentDAO(IEquipmentDAO equipmentDAO) {
        this.equipmentDAO = equipmentDAO;
    }



}
